<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录音功能示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f5f5f5;
        }
        
        .recorder-container {
            text-align: center;
        }
        
        #recordButton {
            padding: 15px 30px;
            font-size: 18px;
            background-color: #ff4444;
            color: white;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            outline: none;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
        }
        
        #recordButton:active {
            transform: scale(0.95);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        #recordButton.recording {
            background-color: #44ff44;
            animation: pulse 1.5s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        #status {
            margin-top: 20px;
            font-size: 16px;
            color: #666;
        }
        
        #audioPlayback {
            margin-top: 20px;
            width: 100%;
            max-width: 300px;
        }
    </style>
</head>
<body>
    <div class="recorder-container">
        <h1>录音功能演示</h1>
        <button id="recordButton">按住录音</button>
        <p id="status">准备录音...</p>
        <audio id="audioPlayback" controls autoplay></audio>
    </div>

    <script>
        const recordButton = document.getElementById('recordButton');
        const statusDisplay = document.getElementById('status');
        const audioPlayback = document.getElementById('audioPlayback');
        
        let mediaRecorder;
        let audioChunks = [];
        function blobToBase64(blob) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onloadend = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(blob);
            });
        }
        function base64ToBlob(base64) {
            const bytes = atob(base64);
            const byteArr = new Uint8Array(bytes.length);
            for (let i = 0; i < bytes.length; i++) {
                byteArr[i] = bytes.charCodeAt(i);
            }
            return new Blob([byteArr], {
                type: "audio/wav"
            });
        }
        // 请求麦克风权限
        recordButton.addEventListener('mousedown', async () => {
            try {
                const constraints = {
                    audio: {
                        channelCount: 1,
                        sampleRate: 8000,
                        volume: 1
                    }
                }
                // const stream = await navigator.mediaDevices.getUserMedia({ audio: constraints });
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                
                mediaRecorder.ondataavailable = event => {
                    audioChunks.push(event.data);
                };
                
                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    //const base64Audio = await blobToBase64(audioBlob);
                    //console.log(base64Audio)
                    const formData = new FormData();
                    const timestamp = Date.now();
                    formData.append('audio', audioBlob, 'recording.wav');
                    formData.append('timestamp', timestamp);
                    const response = await fetch('http://localhost:8088/speaker-api/chat/init', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer sk-5d2090a0ac394b218376b67cb91123f5'
                        },
                        mode: 'cors',
                        body: formData,
                    });
                    
                    if (!response.ok) {
                        throw new Error('Failed to connect to SSE endpoint');
                    }

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();

                    let res = null
                    while (true) {
                        const { value, done } = await reader.read();
                        if (done) {
                            break;
                        }

                        // Decode the chunk and split into events (assuming newline-separated)
                        const chunk = decoder.decode(value);
                        const events = chunk.split('\n');
                        // Process each event
                        events.forEach((event) => {
                            console.log(event)
                        });
                    }
                    // const audioUrl = URL.createObjectURL(audioBlob);
                    // audioPlayback.src = audioUrl;
                    audioChunks = [];
                    // const blob = base64ToBlob(res);
                    audioPlayback.src = "http://localhost:8088/speaker-api/static/" + timestamp + ".mp3";

                    // 停止所有轨道
                    stream.getTracks().forEach(track => track.stop());
                };
                
                mediaRecorder.start();
                recordButton.classList.add('recording');
                statusDisplay.textContent = "录音中...释放按钮结束录音";
            } catch (error) {
                statusDisplay.textContent = "无法访问麦克风: " + error.message;
                console.error("录音错误:", error);
            }
        });
        
        recordButton.addEventListener('mouseup', () => {
            if (mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
                recordButton.classList.remove('recording');
                statusDisplay.textContent = "录音完成! 点击下方播放按钮收听";
            }
        });
        
        // 触摸设备支持
        recordButton.addEventListener('touchstart', async (e) => {
            e.preventDefault();
            recordButton.dispatchEvent(new Event('mousedown'));
        });
        
        recordButton.addEventListener('touchend', (e) => {
            e.preventDefault();
            recordButton.dispatchEvent(new Event('mouseup'));
        });
    </script>
</body>
</html>